package com.hwy.simple.chart.line_chart

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.util.AttributeSet
import android.widget.LinearLayout
import android.widget.TextView
import com.hwy.chart.cursor.OnCursorChangeListener
import com.hwy.simple.chart.R

/**
 * =======================================
 * 作者: hewenyu
 * 日期: 2022/5/11 18:56
 * 说明:
 * =======================================
 */
class LineChartLegend @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : LinearLayout(context, attrs), OnCursorChangeListener {

    private val timeTv by lazy {
        findViewById<TextView>(R.id.time_tv)
    }

    private val totalBuyTv by lazy {
        findViewById<TextView>(R.id.total_buy_tv)
    }

    private val shBuyTv by lazy {
        findViewById<TextView>(R.id.sh_buy_tv)
    }

    private val szBuyTv by lazy {
        findViewById<TextView>(R.id.sz_buy_tv)
    }

    var lineChartBean: LineChartBean? = null

    override fun onFinishInflate() {
        super.onFinishInflate()
        background = GradientDrawable().apply {
            setColor(Color.parseColor("#CC000000"))
            cornerRadius = 20F
        }
    }

    override fun onCursorChange(fromIndex: Int?, toIndex: Int?) {
        lineChartBean?.run {
            toIndex?.let { index ->
                timeTv.text = "${data.date} ${data.net_buy_time_list[index]}"
                totalBuyTv.text = "${formatData(data.total_net_buy_list[index])}亿"
                shBuyTv.text = "${formatData(data.sh_net_buy_list[index])}亿"
                szBuyTv.text = "${formatData(data.sz_net_buy_list[index])}亿"
            }
        }
    }

    private fun formatData(data: Float?): String {
        return data?.run {
            String.format("%.2f", this)
        } ?: "--"
    }

}